package com.mirror.tk.api.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.base.Throwables;
import com.mirror.tk.framework.common.web.support.JsonResult;
import com.mirror.tk.framework.utils.mapper.JsonMapper;

/**
 * 全局异常处理基类
 * 已处理针对ajax请求返回页面处理
 * 该基类可自行继承已适应不同的环境
 */
public class BaseGlobalExceptionHandler {

	protected static final Logger logger = LogManager.getLogger();

	protected static final String DEFAULT_ERROR_MESSAGE = "系统忙，请稍后再试";

	protected ModelAndView handleError(HttpServletRequest req, HttpServletResponse rsp, Exception e, String viewName, HttpStatus status) throws Exception {
		if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
			throw e;
		String errorMsg = e instanceof Exception ? e.getMessage() : DEFAULT_ERROR_MESSAGE;
		String errorStack = Throwables.getStackTraceAsString(e);
		logger.error("Request: {} raised {}", req.getRequestURI(), errorStack);
		// 如果为ajax返回json 否则 返回页面
		if ((req.getHeader("x-requested-with") != null	&& req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) || (req.getRequestURI() != null && req.getRequestURI().indexOf("ajax") != -1 || req.getAttribute("ajax") != null)) {
			return handleAjaxError(rsp, errorMsg, status);
		}
		return handleViewError(req.getRequestURL().toString(), errorStack, errorMsg, viewName);
	}

	protected ModelAndView handleViewError(String url, String errorStack, String errorMessage, String viewName) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("exception", errorStack);
		mv.addObject("url", url);
		mv.addObject("message", errorMessage);
		mv.addObject("timestamp", new Date());
		mv.setViewName(viewName);
		return mv;
	}

	protected ModelAndView handleAjaxError(HttpServletResponse rsp, String errorMessage, HttpStatus status) throws IOException {
		rsp.setCharacterEncoding("UTF-8");
		rsp.setStatus(status.value());
        PrintWriter printWriter = rsp.getWriter();
        printWriter.write(JsonMapper.nonDefaultMapper().toJson(new JsonResult(String.valueOf(status.value()), errorMessage)));
        printWriter.flush();
        printWriter.close();
		return null;
	}
	
}
